use clap::{ArgMatches, App, AppSettings, SubCommand, Arg};
use std::process::exit;
use crate::storage::Storage;

pub fn get_matches<'a>() -> ArgMatches<'a> {
    let matches = App::new(env!("CARGO_PKG_NAME"))
        .version(env!("CARGO_PKG_VERSION"))
        .author(env!("CARGO_PKG_AUTHORS"))
        .about(env!("CARGO_PKG_DESCRIPTION"))
        .setting(AppSettings::DisableHelpSubcommand)
        .setting(AppSettings::SubcommandRequiredElseHelp)
        .setting(AppSettings::VersionlessSubcommands)
        .subcommand(
            SubCommand::with_name("set")
                .about("Set the value of a string key to a string")
                .arg(Arg::with_name("KEY").help("A string key").required(true))
                .arg(
                    Arg::with_name("VALUE")
                        .help("The string value of the key")
                        .required(true),
                ),
        )
        .subcommand(
            SubCommand::with_name("get")
                .about("Get the string value of a given string key")
                .arg(Arg::with_name("KEY").help("A string key").required(true)),
        )
        .subcommand(
            SubCommand::with_name("rm")
                .about("Remove a given key")
                .arg(Arg::with_name("KEY").help("A string key").required(true)),
        )
        .get_matches();
    matches
}

pub fn do_match( storage: &mut impl Storage, matches: ArgMatches) -> ! {
    match matches.subcommand() {
        ("set", Some(m_matches)) => {
            storage.set(get_arg(m_matches, "KEY"), get_arg(m_matches, "VALUE"));
            exit(0);
        }
        ("get", Some(m_matches)) => {
            storage.get(get_arg(m_matches, "KEY"));
            exit(0);
        }
        ("rm", Some(m_matches)) => {
            storage.remove(get_arg(m_matches, "KEY"));
            exit(0);
        }

        _ => {
            println!("unSupported operation");
            exit(1)
        }
    }
}

fn get_arg(m_matches: &ArgMatches, key: &str) -> String {
    match m_matches.value_of(key) {
        Some(arg) => arg.to_string(),
        _ => { panic!("请输入对应的值:{}", key) }
    }
}
